package com.yz.xyt.controller;

import com.github.pagehelper.PageInfo;
import com.yz.xyt.constant.Constants;
import com.yz.xyt.constant.HttpStatus;
import com.yz.xyt.domain.Leave;
import com.yz.xyt.domain.LeaveRule;
import com.yz.xyt.domain.ResponseResult;
import com.yz.xyt.domain.vo.LeaveVo;
import com.yz.xyt.service.IFileService;
import com.yz.xyt.service.ILeaveRuleService;
import com.yz.xyt.service.ILeaveService;
import com.yz.xyt.utils.SecurityUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;


/**
 * 请假controller
 * @author JW.WANG
 */
@RestController
@RequestMapping("/leave")
public class LeaveController {

    @Autowired
    ILeaveService leaveService;

    @Autowired
    IFileService fileService;

    @Autowired
    ILeaveRuleService leaveRuleService;

    /**
     * 检查是否在请假中
     * @return
     */
    @PostMapping("/isAllowApply")
    public ResponseResult isAllowApply(){

        ResponseResult result = new ResponseResult();

        Integer studentNumber = Integer.valueOf(SecurityUtils.getUsername());
        Boolean inLeave = leaveService.selectInLeaveByStudentNumber(studentNumber);
        Boolean leaveEr =  leaveService.selectErrorLeaveByStudentNumber(studentNumber);

        if(inLeave || leaveEr){
            result.setMsg("不允许请假");
            result.setCode(HttpStatus.NOT_ALLOW_APPLY_LEAVE);
        }
        if(!inLeave && !leaveEr){
            result.setMsg("允许请假");
            result.setCode(HttpStatus.SUCCESS);
        }

        return result;
    }

    /**
     * 报备请假
     * @param leave
     * @return
     */
    @PostMapping("/reportLeave")
    public ResponseResult reportLeave(Leave leave){
        ResponseResult result = new ResponseResult();
        //报备请假是否能用
        LeaveRule rule = leaveRuleService.selectIsUseRule();
        System.out.println("=========");
        System.out.println(leave);
        System.out.println("=========");

        if(rule == null || rule.getRuleName().equals(Constants.REPORT_LEAVE_RULE_OFF)){
            result.setCode(HttpStatus.ERROR);
            result.setMsg("报备请假已关闭，请移步审批请假");
            return result;
        }

        //设置请求类型为报备请假
        leave.setStudentNumber(SecurityUtils.getUsername());
        if(StringUtils.isNotEmpty(leave.getLeaveType())){
            String leaveType = leave.getLeaveType();
            if (!Constants.LEAVE_TYPE_REPORT.equals(leaveType)) {
                result.setCode(HttpStatus.ERROR);
                result.setMsg("请申请审批请假");
                return result;
            }
        }
        leave.setLeaveType(Constants.LEAVE_TYPE_REPORT);
        result = leaveService.reportLeave(leave);
        return result;
    }

    /**
     * 常规请假
     * @param leave
     * @return
     */
    @PostMapping("/normalLeave")
    public ResponseResult normalLeave(Leave leave) throws IOException{
        //存放佐证材料
        if(leave.getFile() !=null){
            String filePath = fileService.uploadFile("", leave.getFile());
            leave.setDocument(filePath);
        }
        ResponseResult result = new ResponseResult();
        if (StringUtils.isNotEmpty(leave.getLeaveType())){
            String leaveType = leave.getLeaveType();
            if(Constants.LEAVE_TYPE_REPORT.equals(leaveType)){
                result.setMsg("请申请报备请假");
                result.setCode(HttpStatus.ERROR);
                return  result;
            }
        }else{
            result.setMsg("请假失败，请假类型不能为空");
            result.setCode(HttpStatus.ERROR);
            return  result;
        }
        result= leaveService.normalLeave(leave);
        return result;
    }

    /**
     * 请假审批
     * @param leave
     * @return
     */
    @PostMapping("/approvalLeave")
    public ResponseResult approvalLeave(Leave leave){
        ResponseResult result = new ResponseResult();
        Leave approvalLeave = new Leave();
        approvalLeave.setId(leave.getId());
        //获取当前用户角色
        List<String> userRoles = SecurityUtils.getLoginUser().getRoles();
        if(userRoles.contains(Constants.APPROVAL_ROLE_FD)){
            //辅导员审核
            leaveService.instructorApproval(approvalLeave);
        }else if(userRoles.contains(Constants.APPROVAL_ROLE_SJ)){
            //书记审核
            leaveService.secretaryApproval(approvalLeave);
        }else if (userRoles.contains(Constants.APPROVAL_ROLE_XSC)){
            //学生处审核
            leaveService.studentOfficeApproval(approvalLeave);
        }else if(userRoles.contains(Constants.APPROVAL_ROLE_FGLD)){
            //分管领导审核
            leaveService.leaderApproval(approvalLeave);
        }else {
            result.setMsg("审核失败");
            result.setCode(HttpStatus.APPROVAL_LEAVE_FAILED);
        }

        result.setMsg("审核成功");
        result.setCode(HttpStatus.SUCCESS);
        return result;
    }

    /**
     * 驳回申请
     * @param leave
     * @return
     */
    @PostMapping("/rejectApply")
    public ResponseResult rejectApply(Leave leave){
        ResponseResult result = new ResponseResult();
        //获取数据库中的记录
        Leave record = leaveService.selectByPrimaryKey(leave.getId());
        if (!leaveService.isAllowReject(record)){
            result.setMsg("不能拒绝，请假已审批或请假已完成");
            result.setCode(HttpStatus.ERROR);
            return result;
        }
        Leave approvalLeave = new Leave();
        approvalLeave.setId(leave.getId());
        approvalLeave.setRefuseReason(leave.getRefuseReason());

        leaveService.rejectApply(approvalLeave);
        result.setMsg("拒绝请假成功");
        result.setCode(HttpStatus.SUCCESS);
        return result;
    }

    /**
     * 请假撤销
     * @param leave
     * @return
     */
    @PostMapping("/cancelLeave")
    public ResponseResult cancelLeave(Leave leave){
        ResponseResult result = new ResponseResult();
        leave = leaveService.selectByPrimaryKey(leave.getId());
        if (!Constants.APPROVAL_WAIT.equals(leave.getApprovalStatus())){
            result.setCode(HttpStatus.ERROR);
            result.setMsg("请假审批中，不能撤销");
            return result;
        }
        Leave approvalLeave = new Leave();
        approvalLeave.setId(leave.getId());
        leaveService.cancelLeave(approvalLeave);
        result.setMsg("撤销成功");
        result.setCode(HttpStatus.SUCCESS);
        return result;
    }

    /**
     * 获取请假佐证材料
     * @param id
     * @return
     */
    @GetMapping("/download")
    public ResponseEntity<byte[]> fileDownload(Integer id){
        //获取请假信息中存放的文件地址
        Leave leave = leaveService.selectByPrimaryKey(id);
        String path = leave.getDocument();
        //创建文件对象
        File file = new File(path);
        //获取文件名
        String fileName = file.getName();
        //设置响应头信息
        HttpHeaders headers = new HttpHeaders();
        //设置浏览器以下载的方式打开文件
        headers.setContentDispositionFormData("attachment",fileName);
        //定义以流的形式下载返回文件数据
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        try {
            return  new ResponseEntity(FileUtils.readFileToByteArray(file),headers, org.springframework.http.HttpStatus.OK);
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseEntity<>(e.getMessage().getBytes(), org.springframework.http.HttpStatus.EXPECTATION_FAILED);
        }
    }




    /**
     * 获取请假列表
     * @param leaveVo
     * @return
     */
    @RequestMapping("/getLeaveList")
    public ResponseResult getLeaveList(LeaveVo leaveVo){
        ResponseResult result = new ResponseResult();
        String status = leaveVo.getStatus();
        PageInfo pageInfo;

        //增加我已审批判断
        if (Constants.MY_APPROVAED.equals(status)){
            pageInfo = leaveService.queryApprovedLeaveForPage(leaveVo);
        }else{
            pageInfo = leaveService.queryForPage(leaveVo);
        }
        result.setCode(HttpStatus.SUCCESS);
        result.setMsg("查询成功");
        result.setData(pageInfo);

        return result;
    }

    /**
     * 辅导员 处理 超时未销假
     */
    @RequestMapping("/dealLeaveTimeOutNotCancel")
    public ResponseResult dealLeaveTimeOutNotCancel(Leave leave){
        return leaveService.dealLeaveTimeOutNotCancel(leave);
    }

    /**
     * 显示请假图片
     * @param id
     * @return
     */
    @GetMapping(value = "/img",produces = MediaType.IMAGE_JPEG_VALUE)
    public byte[] showImg(Integer id) throws Exception{
        Leave leave = leaveService.selectByPrimaryKey(id);
        if (StringUtils.isNotEmpty(leave.getDocument())){
            File file = new File(leave.getDocument());
            FileInputStream in = new FileInputStream(file);
            byte[] bytes = new byte[in.available()];
            in.read(bytes,0,in.available());
            return bytes;
        }else {
            return new byte[0];
        }
    }

    /**
     * 销假
     * @param leave
     * @return
     */
    @PostMapping("/expended")
    public ResponseResult expendedLeave(Leave leave){
        ResponseResult result = new ResponseResult();
        Leave approvalLeave = new Leave();
        approvalLeave.setId(leave.getId());
        int count = leaveService.expendedLeave(approvalLeave);
        if (count > 0){
            result.setMsg("销假成功");
            result.setCode(HttpStatus.SUCCESS);
        }else{
            result.setCode(HttpStatus.ERROR);
            result.setMsg("销假失败");
        }
        return result;
    }

    /**
     * 批量审批
     * @param ids
     * @return
     */
    @RequestMapping("/batchAgree")
    public ResponseResult batchAgree(String ids){
        ResponseResult result = new ResponseResult();
        if (StringUtils.isEmpty(ids)){
            result.setMsg("参数错误");
            result.setCode(HttpStatus.ERROR);
            return result;
        }

        List<String> roles = SecurityUtils.getLoginUser().getRoles();
        if (roles.contains(Constants.APPROVAL_ROLE_FD)){
            result.setCode(HttpStatus.ERROR);
            result.setMsg("不能批量审批");
            return result;
        }
        //获取批量审批的请假id
        List<String> idList = Arrays.asList(ids.split(","));
        result = leaveService.batchAgree(idList);
        return result;
    }

    /**
     * 获取我已审批的请假列表
     * @return
     */
    @RequestMapping("getApprovedList")
    public ResponseResult getApprovedList(LeaveVo leaveVo){
        ResponseResult result = new ResponseResult();
        PageInfo pageInfo = leaveService.queryApprovedLeaveForPage(leaveVo);
        result.setCode(HttpStatus.SUCCESS);
        result.setMsg("查询成功");
        result.setData(pageInfo);
        return result;
    }
}
